package com.zy.baselib.widget

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.util.Log
import android.view.animation.LinearInterpolator
import android.widget.Scroller
import androidx.appcompat.widget.AppCompatTextView



/**
 * Created by jdw on 2019/1/22.
 *
 * 解决marquee与动画冲突问题.
 * 完全重现系统marquee表现
 */
class Marquee2TextView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null) : AppCompatTextView(context, attributeSet) {
    private val slr = Scroller(context, LinearInterpolator())
    private var realText: CharSequence = ""
    /**
     * 用于循环调度, 不能使用getHandler, removeCallbacksAndMessages会影响其他主线程消息
     */
    private val myHandler = Handler(Looper.myLooper()!!)
    private var mCount = 0
    private var onMarqueeStopListener: (()->Unit)? = null

    init {
        setSingleLine()
        ellipsize = null
        setScroller(slr)

        postDelayed({ refreshScrollText() }, MARQUEE_DELAY.toLong())
    }

    fun setMarqueeCount(count: Int) {
        this.mCount = count
    }

    fun setTextMarquee(charSequence: CharSequence) {
        slr.forceFinished(true)
        myHandler.removeCallbacksAndMessages(null)
        realText = ""
        text = charSequence

        myHandler.postDelayed({ refreshScrollText() }, MARQUEE_DELAY.toLong())
    }

    private fun refreshScrollText() {
        // 字体长度
        var scrollingLen = paint.measureText(text.toString()).toInt()
        // 总长度
        val distance = scrollingLen + compoundPaddingLeft + compoundPaddingRight
        if (width >= distance) {
            Log.e("refreshScrollText", "x")
            return
        }

        // 这里添加空格
        realText = text.toString()
        val black = StringBuilder("  ")
        while (paint.measureText(black.toString()) < width / 3) {
            black.append(" ")
        }
        append(black)

        // 新的字体长度
        scrollingLen = paint.measureText(text.toString()).toInt()
        // 滚动时长
        val duration = text.length * 400

        append(realText.toString() + black)

        startCircleMarquee(scrollingLen, duration)
    }

    public fun setOnMarqueeStopListener(onMarqueeStopListener: ()->Unit) {
        this.onMarqueeStopListener = onMarqueeStopListener
    }

    private fun startCircleMarquee(distance: Int, duration: Int) {
        slr.startScroll(0, 0, distance, 0, duration)
        invalidate()
        myHandler.postDelayed({ startCircleMarquee(distance, duration) }, duration.toLong() + MARQUEE_DELAY)
    }

    companion object {
        private const val MARQUEE_DELAY = 1200
    }
}